package top.lingkang.mm.transaction;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.transaction.Transaction;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Author lingkang
 * @Date 2024/2/29 14:00
 */
@Slf4j
public class MagicTransaction implements Transaction {

    private final DataSource dataSource;

    private Connection connection;

    public MagicTransaction(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public Connection getConnection() throws SQLException {
        // 从事务管理器中获取事务
        connection = TransactionManage.getConnection(dataSource);
        return connection;
    }

    @Override
    public void commit() throws SQLException {
        if (TransactionManage.isTransaction())
            connection.commit();
    }

    @Override
    public void rollback() throws SQLException {
        if (TransactionManage.isTransaction())
            connection.rollback();
    }

    @Override
    public void close() throws SQLException {
        if (connection != null)
            connection.close();
    }

    @Override
    public Integer getTimeout() throws SQLException {
        return connection.getNetworkTimeout();
    }
}
